package org.dfl.plugin.views.palette;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dfl.core.utils.Utils;
import org.dfl.messages.Messages;
import org.dfl.plugin.views.palette.model.PaletteEntry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;

/**
 * label provider for PaletteView
 * @author Piotr Wlodarczyk
 *
 */
public class PaletteLabelProvider extends LabelProvider {	
	private Map<ImageDescriptor,Image> imageCache = new HashMap<ImageDescriptor,Image>();
	
	/*
	 * @see ILabelProvider#getImage(Object)
	 */
	public Image getImage(Object element) {
		ImageDescriptor descriptor = null;
		if (element instanceof PaletteEntry) {
			descriptor = ((PaletteEntry)element).getImage();
		}else{
			throw unknownElement(element);
		}

		//obtain the cached image corresponding to the descriptor
		Image image = (Image)imageCache.get(descriptor);
		if (image == null) {
			image = descriptor.createImage();
			imageCache.put(descriptor, image);
		}
		return image;
	}

	/*
	 * @see ILabelProvider#getText(Object)
	 */
	public String getText(Object element) {
		if (element instanceof PaletteEntry) {
			return Utils.stripTags(((PaletteEntry)element).getLabel());
		} else {
			throw unknownElement(element);
		}
	}

	public void dispose() {
		for (Iterator<Image> i = imageCache.values().iterator(); i.hasNext();) {
			((Image) i.next()).dispose();
		}
		imageCache.clear();
	}

	protected RuntimeException unknownElement(Object element) {
		return new RuntimeException(Messages.PaletteLabelProvider_errorUnknownType + element.getClass().getName());
	}

}
